#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""journey_image_item collection has
    userid:         用户id（int）
    markid:         景点评论id（int）
    imgid:          s景点照片id（int）
    imgname:        s景点照片文件名（string）
    ctime:          景点照片拍摄时间（datetime），由客户端生成
"""

journey_image_table_dict = {}


class JourneyImageTables(object):
    def make_table(self, p_cityid):
        if journey_image_table_dict.has_key(p_cityid):
            return journey_image_table_dict[p_cityid]

        class JourneyImageItem(object):
            def __init__(self, p_cityid):
                self.p_cityid = p_cityid

            def to_dict(self):
                res = {}
                res['userid'] = self.userid
                res['markid'] = self.markid
                res['imgid'] = self.imgid
                res['imgname'] = self.imgname
                res['ctime'] = self.ctime
                return res

            def __repr__(self):
                return "%d" % (self.userid)

        metadata = MetaData()
        journey_image_item_table = Table(
            'journey_img_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('userid', Integer, index=True, nullable=False),
            Column('markid', Integer, index=True, nullable=False),
            Column('imgid', Integer, index=True, nullable=False),
            Column('imgname', Unicode(40), nullable=False),
            Column('ctime', DateTime, nullable=False))
        mapper(JourneyImageItem, journey_image_item_table)
        table = {'metadata': metadata,
                 'table': journey_image_item_table,
                 'class': JourneyImageItem}
        journey_image_table_dict[p_cityid] = table
        return table


def create_journey_image_item_table_if_not_exist(p_cityid):
    table = JourneyImageTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


def add_journey_image_item(p_cityid, p_item):
    table = JourneyImageTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.userid = p_item['userid']
    item.markid = p_item['markid']
    item.imgid = p_item['imgid']
    item.imgname = p_item['imgname']
    item.ctime = p_item['ctime']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def get_journey_image_all_by_cityid_userid_markid(p_cityid, p_userid, p_markid):
    try:
        session = Session()
        table = JourneyImageTables().make_table(p_cityid)
        items = session.query(table['class'].imgname, table['class'].imgid, table['class'].ctime).filter_by(
            userid=p_userid, markid=p_markid).all()
        img_list = []
        for item in items:
            tmp = {
                'imgid': item.imgid,
                'imgname': item.imgname,
                'ctime': item.ctime
            }
            img_list.append(tmp)
        return img_list
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
        # session.remove()


'''
markid: list
{
1: [{'markid' :1, "imgid": 1,"img_url":"", "ctime": "2015-04-02" }{'markid' :1,"imgid": 1,"img_url":"", "ctime": "2015-04-02" }]
2: [{'markid' :2, "imgid": 1,"img_url":"", "ctime": "2015-04-02" }{'markid' :2,"imgid": 1,"img_url":"", "ctime": "2015-04-02" }]
}
'''


def get_journey_image_all_by_cityid_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyImageTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by(userid=p_userid).all()

        res = []
        img_list = {}
        for item in items:
            temp = item.to_dict()
            res.append(temp)
            if temp['ctime']:
                temp['ctime'] = temp['ctime'].strftime("%Y-%m-%d %H:%M:%S")
            img_list[temp['markid']] = []

        # img_list = {x : [] for x in set(x['markid'] for x in items)}
        for item in res:
            img_list[item['markid']].append(item)

        return img_list
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_journey_imgid_list_by_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyImageTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by(userid=p_userid).all()
        imgid_list = [item.imgid for item in items]
        return imgid_list
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def delete_journey_img_by_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyImageTables().make_table(p_cityid)
        item = session.query(table['class']).filter_by(userid=p_userid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    test_city = 1
    create_journey_image_item_table_if_not_exist(test_city)

    print get_journey_imgid_list_by_userid(1, 111)

    # test_item = {'userid': 1,
    #             'markid': 1,
    #             'imgid': 1,
    #             'ctime': datetime.now() }
    # add_journey_image_item(test_city, test_item)
    '''
    journey_image_dict = get_journey_image_all_by_cityid_userid(1, 113)
    print journey_image_dict
    print "============"
    
    if journey_image_dict :
        count =1
        for item_markid in journey_image_dict.values():
            
            if count == 1 : print item_markid
            if count == 1 : print "=====1111======="
            
            
            for image_dict in item_markid:
                imgid = image_dict['imgid']
                if count == 1 : print image_dict
                if count == 1 : print "======22222======"
                p_item = data_img_base_mysql.get_img_base_by_imgid(imgid)
                if count == 1 : print p_item
                if count == 1 : print "======3333======"
                if p_item :
                    image_dict['img_url'] = 'http://static.shitouren.com/group' + str(p_item['group'])+'/'+str(p_item['path'])+'.'+str(p_item['ext'])
                else :
                    image_dict['img_url'] = ''
                count += 1
                
            if count ==2 :
                break;
    
    print "============"
    print "============"
    print journey_image_dict
    '''
